package com.stylefeng.guns.modular.system.controller;

import com.stylefeng.guns.common.annotion.log.BussinessLog;
import com.stylefeng.guns.common.constant.Dict;
import com.stylefeng.guns.common.constant.tips.ErrorTip;
import com.stylefeng.guns.common.controller.BaseController;
import com.stylefeng.guns.common.exception.BizExceptionEnum;
import com.stylefeng.guns.common.exception.BussinessException;
import com.stylefeng.guns.common.persistence.dao.OrgClassMapper;
import com.stylefeng.guns.common.persistence.dao.OrgClassTypeMapper;
import com.stylefeng.guns.common.persistence.dao.OrgInfoMapper;
import com.stylefeng.guns.common.persistence.dao.OrgTeacherMapper;
import com.stylefeng.guns.common.persistence.model.OrgClass;
import com.stylefeng.guns.common.persistence.model.OrgClassType;
import com.stylefeng.guns.common.persistence.model.OrgInfo;
import com.stylefeng.guns.common.persistence.model.OrgTeacher;
import com.stylefeng.guns.config.properties.GunsProperties;
import com.stylefeng.guns.modular.system.dao.OrgClassDao;
import com.stylefeng.guns.modular.system.dao.OrgClassTypeDao;
import com.stylefeng.guns.modular.system.dao.OrgInfoDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.expression.ParseException;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 课程管理控制器
 *
 * @author fengshuonan
 * @Date 2018-08-17 11:17:50
 */
@Controller
@RequestMapping("/orgClass")
public class OrgClassController extends BaseController {

    private String PREFIX = "/system/orgClass/";

    @Autowired
    OrgClassMapper orgClassMapper;
    @Autowired
    OrgTeacherMapper orgTeacherMapper;
    @Autowired
    OrgClassTypeMapper orgClassTypeMapper;
    @Autowired
    OrgInfoMapper orgInfoMapper;
    @Autowired
    CheckAccessUtil checkAccessUtil;
    @Autowired
    OrgClassDao orgClassDao;
    @Autowired
    OrgClassTypeDao orgClassTypeDao;
    @Autowired
    OrgInfoDao orgInfoDao;

    @Resource
    private GunsProperties gunsProperties;
    /**
     * 跳转到课程管理首页
     *
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "orgClass.html";
    }

    /**
     * 跳转到添加课程管理
     */
    @RequestMapping("/orgClass_add")
    public String orgClassAdd() {
        return PREFIX + "orgClass_add.html";
    }

    @RequestMapping("/orgClass_admin_add")
    public String orgClassAdminAdd() {
        return PREFIX + "orgClass_admin_add.html";
    }
    /**
     * 跳转到修改课程管理
     */
    @RequestMapping("/orgClass_update/{orgClassId}")
    public String orgClassUpdate(@PathVariable Integer orgClassId, Model model) {

        OrgClass old=this.orgClassMapper.selectById(orgClassId);

        OrgInfo orgInfos = orgInfoMapper.selectById(old.getInfoId());
        old.setInfoName(orgInfos.getOrgName());
        old.getClassStartTime();
//        SimpleDateFormat xdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//        try{
//
//        }catch (Exception e){
//            e.printStackTrace();
//        }
        OrgClassType orgClassType = orgClassTypeMapper.selectById(old.getClassTypeId());
        old.setClassName(orgClassType.getClassName());


        List<String> orgTeacherIds =Arrays.asList(old.getTeacherId().split(","));
        String teacherName ="";
        for(String id:orgTeacherIds){
            try{
                OrgTeacher orgTeacher = orgTeacherMapper.selectById(id);
                teacherName += orgTeacher.getTeacherName()+',';
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        if("" != teacherName){
            teacherName = teacherName.substring(0,teacherName.length()-1);
        }
        old.setTeacherName(teacherName);
        model.addAttribute("orgClass",old);
        return PREFIX + "orgClass_edit.html";
    }

    /**
     * 获取课程管理列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list() {

        //创建List对象容器
        List<OrgClass> orgClasses = null;
        //获取权限监测返回值
        int infoId =  checkAccessUtil.CheckAccess();
        //  如果返回 -1 表示 userId 不存在 即info_id 不存在
        //  如果返回 0 则表示要查询所有 数据
        //  如果返回 不等于0  则返回值为 info_id
        if(infoId == 0){
            //查询所有对象列表
            orgClasses = orgClassMapper.selectList(null);
        }else if(infoId == -1){
            return null;
        }else{
            //根据infoId 去找到对象信息
            orgClasses = orgClassDao.findByInfoId(infoId);
        }
//判断用户是admin还是普通用户
     for(OrgClass orgClass:orgClasses){
         String infoIds = orgClass.getInfoId();
         OrgInfo orgInfo = orgInfoMapper.selectById(infoIds);
         if (orgInfo != null){
             String orgNames = "";
             orgNames = orgInfo.getOrgName();
             orgClass.setInfoId(orgNames);
         }
     }

        for(OrgClass orgClass:orgClasses){
            List<String> teacherIds = Arrays.asList(orgClass.getTeacherId().split(","));
            String teacherNames = "";
            for(String id:teacherIds){
                try{
                    OrgTeacher orgTeacher = orgTeacherMapper.selectById(id);
                    teacherNames += orgTeacher.getTeacherName()+",";
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if("" != teacherNames){
                teacherNames = teacherNames.substring(0,teacherNames.length()-1);
            }
            orgClass.setTeacherId(teacherNames);
        }

       for(OrgClass orgClass:orgClasses){
           String classTypeIds = orgClass.getClassTypeId();
           String classNames = "";
           OrgClassType orgClassType = orgClassTypeMapper.selectById(classTypeIds);
           classNames = orgClassType.getClassName();
           orgClass.setClassTypeId(classNames);
       }
        return orgClasses;
    }
    @RequestMapping(method = RequestMethod.POST, path = "/upload")
    @ResponseBody
    public String upload(@RequestPart("file") MultipartFile picture) {
        //设置图片为唯一的uuid
        String pictureName = UUID.randomUUID().toString() + ".jpg";
        try {
            //获取上传路径
            String fileSavePath = gunsProperties.getFileUploadPath();
            /**
             * transferTo在开发Web应用程序时比较常见的功能之一，
             * 就是允许用户利用multipart请求将本地文件上传到服务器,
             * Spring通过对ServletAPI的HttpServletRequest接口进行扩展，使其能够很好地处理文件上传
             */
            picture.transferTo(new File(fileSavePath + pictureName));
        } catch (Exception e) {
            throw new BussinessException(BizExceptionEnum.UPLOAD_ERROR);
        }
        return pictureName;
    }
    /**
     * 新增课程管理
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(OrgClass orgClass,String classStartTime1,String classEndTime1){
        if(orgClass !=null){
            orgClass.setCreateDate(new Date());
        }
        int infoId =  checkAccessUtil.CheckAccess();
        if(infoId==0){
        }
        if(infoId==-1){
            return null;
        }else{
            String  infoIds = String.valueOf(infoId);
            orgClass.setInfoId(infoIds);
        }
        if(StringUtils.isEmpty(classStartTime1)||StringUtils.isEmpty(classEndTime1)){
            return new ErrorTip(400,"参数错误");
        }
        String cst=classStartTime1.replace("T", " ");
        String cet=classEndTime1.replace("T"," ");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            orgClass.setClassStartTime(sdf.parse(cst));
            orgClass.setClassEndTime(sdf.parse(cet));
        } catch (Exception e) {
            e.printStackTrace();
        }
        Integer insert = orgClassMapper.insert(orgClass);
        return super.SUCCESS_TIP;
    }
    @RequestMapping(value = "/addAdmin")
    @ResponseBody
    public Object addAdmin(OrgClass orgClass,String classStartTime1,String classEndTime1){
        if(orgClass !=null){
            orgClass.setCreateDate(new Date());
        }
        if(StringUtils.isEmpty(classStartTime1)||StringUtils.isEmpty(classEndTime1)){
            return new ErrorTip(400,"参数错误");
        }
        String cst=classStartTime1.replace("T"," ");
        String cet=classEndTime1.replace("T"," ");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            orgClass.setClassStartTime(sdf.parse(cst));
            orgClass.setClassEndTime(sdf.parse(cet));
        } catch (Exception e) {
            e.printStackTrace();
        }
        Integer insert = orgClassMapper.insert(orgClass);
        return super.SUCCESS_TIP;
    }
    /**
     *
     * 删除课程管理
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    @BussinessLog(value = "删除节点",key = "orgClassId",dict = Dict.DeleteDict)
    public Object delete(@RequestParam Integer orgClassId) {
        this.orgClassMapper.deleteById(orgClassId);
        return SUCCESS_TIP;
    }
    /**
     * 修改课程管理
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    @BussinessLog(value = "修改节点",key = "orgClassId",dict = Dict.DictMap)
    public Object up(OrgClass orgClass) {
//        try{
//
//        }catch (Exception e){
//            e.printStackTrace();
//        }
        Integer update=orgClassMapper.updateById(orgClass);
        return super.SUCCESS_TIP;
    }

    /**
     * 选择课程页
     * @param type
     * @return
     */
    @RequestMapping(value = "/chooseClass")
    public Object chooseClass(Integer type) {
        //1表示单选
        if(2==type){
            return PREFIX + "kid2.html";
        }
        return PREFIX + "kid1.html";
    }

    @RequestMapping(value = "/chooseInfo")
    public Object chooseInfo(){return PREFIX + "infoList.html";}

    /**
     * 选择课程列表数据
     */
    @RequestMapping(value = "/chooseClassList")
    @ResponseBody
    public Object chooseClassList() {

        List<OrgClassType> orgClassTypeList = orgClassTypeDao.findAll();
        return orgClassTypeList;
    }
//    @RequestMapping(value = "/chooseInfoList")
//    @ResponseBody
//    public Object chooseInfoList() {
//        List<OrgInfo> orgInfoList = orgInfoDao.findAll();
//        return orgInfoList;
//    }
    /**
     * 课程管理详情
     */
    @RequestMapping(value = "/detail")
    @ResponseBody
    public Object detail() {
        return null;
    }

}
